package io.renren.modules.sys.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.sys.service.OnshelvesService;
import io.renren.modules.sys.service.OnshelvesitemService;
import io.renren.modules.sys.service.ProductshelvesstcokService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * 
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2019-03-25 18:07:20
 */
@RestController
@RequestMapping("sys/onshelves")
public class OnshelvesController {
    @Autowired
    private OnshelvesService onshelvesService;

    @Autowired
    private OnshelvesitemService onnshelvesitemService;


    @Autowired
    private ProductshelvesstcokService productshelvesstcokService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:onshelves:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = onshelvesService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:onshelves:info")
    public R info(@PathVariable("id") Integer id){
        OnshelvesEntity onshelves = onshelvesService.getById(id);

        return R.ok().put("onshelves", onshelves);
    }

    /**
     * 信息
     */
    @RequestMapping("/infoById/{id}")
    @RequiresPermissions("sys:onshelves:infoById")
    public R infoById(@PathVariable("id") Integer id){
        OnshelvesVOEntity onshelves = onshelvesService.getInfoById(id);

        return R.ok().put("onshelves", onshelves);
    }

    /**
     * 统计信息
     */
    @RequestMapping("/infoStatistics")
    @RequiresPermissions("sys:onshelves:infoStatistics")
    public R infoStatistics(@RequestParam Map<String, Object> params){
        OnshelvesStatisticsEntity onshelves = onshelvesService.getStatistics(params);

        return R.ok().put("onshelves", onshelves);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:onshelves:save")
    public R save(@RequestBody String str){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        JSONObject json = JSONObject.fromObject(str);
        JSONArray arrayShelves = JSONArray.fromObject(json.get("shelvesid"));
        JSONArray arrayProduct = JSONArray.fromObject(json.get("products"));
        int count = 0;
        int price = 0;
        List<OnshelvesEntity>  ids = new ArrayList<OnshelvesEntity>();
        for(int i=0;i<arrayProduct.size();i++){
            count +=arrayProduct.getJSONObject(i).getInt("count");
            price +=count*arrayProduct.getJSONObject(i).getInt("costprice");
        }
        for(int i=0;i<arrayShelves.size();i++){
            OnshelvesEntity onshelvesEntity = new OnshelvesEntity();

            onshelvesEntity.setUppernumber("SJ"+sdf.format(new Date()));
            onshelvesEntity.setShelvesid(arrayShelves.getJSONObject(i).getInt("id"));
            onshelvesEntity.setType(arrayProduct.size());
            onshelvesEntity.setCreatetime(new Date());
            onshelvesEntity.setLasttime(new Date());
            onshelvesEntity.setCreateuser(Integer.parseInt(user.getUserId().toString()));
            onshelvesEntity.setLastuser(Integer.parseInt(user.getUserId().toString()));

            onshelvesEntity.setRemark("");
            onshelvesEntity.setStatu(json.getInt("statu"));
            onshelvesEntity.setNum(count);
            onshelvesEntity.setCost(new BigDecimal(price));
            onshelvesService.save(onshelvesEntity);
            ids.add(onshelvesEntity);
        }

        for(OnshelvesEntity entity:ids){
            for(int i=0;i<arrayProduct.size();i++){
                OnshelvesitemEntity onshelvesitemEntity = new OnshelvesitemEntity();
                onshelvesitemEntity.setProductid(arrayProduct.getJSONObject(i).getInt("id"));
                onshelvesitemEntity.setOncount(arrayProduct.getJSONObject(i).getInt("count"));
                onshelvesitemEntity.setOnshelvesid(entity.getId());
                onshelvesitemEntity.setCostprice(new BigDecimal(arrayProduct.getJSONObject(i).getInt("costprice")));
                onshelvesitemEntity.setSellprice(new BigDecimal(arrayProduct.getJSONObject(i).getInt("sellprice")));
                onshelvesitemEntity.setTotalcost(new BigDecimal(arrayProduct.getJSONObject(i).getInt("count")*arrayProduct.getJSONObject(i).getInt("costprice")));
                onnshelvesitemService.save(onshelvesitemEntity);

                if(json.getInt("statu") ==1){
                    ProductshelvesstcokEntity productshelvesstcokEntity = productshelvesstcokService.getByProductIdAndShelvesId(arrayProduct.getJSONObject(i).getInt("id"),entity.getShelvesid());
                    if(productshelvesstcokEntity!=null){//该商品在该货架已上过架，修改库存数量
                        productshelvesstcokEntity.setStock(productshelvesstcokEntity.getStock()+arrayProduct.getJSONObject(i).getInt("count"));
                        productshelvesstcokService.updateById(productshelvesstcokEntity);
                    }else{//该商品在该货架未上架，添加库存信息
                        productshelvesstcokEntity = new ProductshelvesstcokEntity();
                        productshelvesstcokEntity.setStock(arrayProduct.getJSONObject(i).getInt("count"));
                        productshelvesstcokEntity.setProductid(arrayProduct.getJSONObject(i).getInt("id"));
                        productshelvesstcokEntity.setShelvesid(entity.getShelvesid());
                        productshelvesstcokService.save(productshelvesstcokEntity);
                    }
                }

            }
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:onshelves:update")
    public R update(@RequestBody String str){
        JSONObject json = JSONObject.fromObject(str);
        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        OnshelvesEntity onshelves = onshelvesService.getById(json.getInt("id"));
        onshelves.setLasttime(new Date());
        onshelves.setLastuser(Integer.parseInt(user.getUserId().toString()));
        onshelves.setStatu(json.getInt("statu"));
        ValidatorUtils.validateEntity(onshelves);
        onshelvesService.updateById(onshelves);

        if(json.getInt("statu") ==1){
            JSONArray arrayProduct = JSONArray.fromObject(json.get("products"));
            for(int i=0;i<arrayProduct.size();i++){
                ProductshelvesstcokEntity productshelvesstcokEntity = productshelvesstcokService.getByProductIdAndShelvesId(arrayProduct.getJSONObject(i).getInt("id"),onshelves.getShelvesid());
                if(productshelvesstcokEntity!=null){//该商品在该货架已上过架，修改库存数量
                    productshelvesstcokEntity.setStock(productshelvesstcokEntity.getStock()+arrayProduct.getJSONObject(i).getInt("count"));
                    productshelvesstcokService.updateById(productshelvesstcokEntity);
                }else{//该商品在该货架未上架，添加库存信息
                    productshelvesstcokEntity = new ProductshelvesstcokEntity();
                    productshelvesstcokEntity.setStock(arrayProduct.getJSONObject(i).getInt("count"));
                    productshelvesstcokEntity.setProductid(arrayProduct.getJSONObject(i).getInt("id"));
                    productshelvesstcokEntity.setShelvesid(onshelves.getShelvesid());
                    productshelvesstcokService.save(productshelvesstcokEntity);
                }
            }

        }

        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:onshelves:delete")
    public R delete(@RequestBody Integer[] ids){
        onshelvesService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
